package com.leaf.lowcode.utils.jsontobean;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.Iterator;


public class JsonToBeanV<T> {
    public T tansfrom(T cls, JSONObject arry){
        // System.out.println("json"+jsonArray);
        JSONObject json = arry;
        if (json.keySet() == null) {
            System.out.println("Invalid data: "+ json.keySet());
            return cls;
        }
        Field[] fields =cls.getClass().getDeclaredFields();
        for(Field field:fields)
        {
            Iterator<String> iterator = json.keySet().iterator();
            while (iterator.hasNext())
            {
                String name = iterator.next();
                if (field.getName().equals(name)) {
                    // System.out.println(name);
                    Object o = json.get(name);
                    /**
                     * 防止属性值为空
                     */
                    if (o == null)
                        o=0;
                    ToTranfer toTranfer =null;
                    //  System.out.println("field.getType():"+field.getType().toString());
                    String valueName =field.getType().toString();
                    switch (valueName) {
                        case "class java.lang.String":
                            //System.out.println("String");
                            toTranfer=new StringToTransfer();
                            cls= (T) toTranfer.laod(field,o,cls);
                            //System.out.println("cls===="+cls.toString());
                            break;
                        case "double":
                            toTranfer=new DoulbeToTransfer();
                            cls= (T) toTranfer.laod(field,o,cls);
                            break;
                    }
                }
            }
        }

        return cls;
    }
}